import { useCallback } from 'react';
import { useSnackbar } from 'notistack';

/**
 * 通用文件导出 Hook
 * 提供文件导出功能，支持自定义数据转换和错误处理
 */
export function useFileExport<T = unknown>() {
  const { enqueueSnackbar } = useSnackbar();

  const exportFile = useCallback(
    (
      data: T,
      filename: string = 'export.json',
      options?: {
        format?: (data: T) => string;
        onSuccess?: () => void;
        onError?: (error: Error) => void;
      }
    ) => {
      try {
        // 使用自定义格式化函数或默认 JSON.stringify
        const formatData = options?.format || ((d: T) => JSON.stringify(d, null, 2));
        const content = formatData(data);

        // 创建 Blob 对象并触发文件下载
        const blob = new Blob([content], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);

      enqueueSnackbar('导出成功！', { variant: 'success' });
      options?.onSuccess?.();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '导出失败';
      console.error('导出失败:', error);
      enqueueSnackbar(`导出失败: ${errorMessage}`, { variant: 'error' });
      if (error instanceof Error) {
        options?.onError?.(error);
      }
    }
    },
    [enqueueSnackbar]
  );

  return { exportFile };
}

